/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.plechinger.mcremote.client;

import com.plechinger.mcremote.data.Request;
import com.plechinger.mcremote.data.Response;
import com.plechinger.mcremote.security.SecurityUtil;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.NoSuchPaddingException;

/**
 *
 * @author Lukas
 */
public class Connector {

    private InetAddress addr;
    private int port;

    public Connector(String hostname, int port) throws UnknownHostException {
        this.addr = InetAddress.getByName(hostname);
        this.port = port;
    }

    public Response send(Request request) throws IOException, ClassNotFoundException, InvalidKeyException {

        Socket socket = new Socket(addr, port);
        OutputStream os = socket.getOutputStream();
        InputStream is = socket.getInputStream();

        is = new DataInputStream(is);
        os = new DataOutputStream(os);

//        Key k = ClientSettings.getSettings().getEncryptionKey();
//        try {
//            is = SecurityUtil.getCipherInputStream(is, k);
//            os = SecurityUtil.getCipherOutputStream(os, k);
//        } catch (NoSuchAlgorithmException ex) {
//            Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (NoSuchPaddingException ex) {
//            Logger.getLogger(Connector.class.getName()).log(Level.SEVERE, null, ex);
//        }


        ObjectOutputStream oos = new ObjectOutputStream(os);
        ObjectInputStream ois = new ObjectInputStream(is);

        oos.writeObject(request);
        oos.flush();
        Object answer = ois.readObject();

        oos.close();
        ois.close();
        if (answer instanceof Response) {
            return (Response) answer;
        } else {
            throw new RuntimeException("Bad Response");
        }
    }
}
